<template>
  <el-card class="report" :shadow="shadowShow" v-loading="loading">
    <div slot="header" class="header">
      <el-select
        v-model="examineTyle"
        size="small"
        :placeholder="$t('caseorder.anli35')"
        @change="typeChange"
        :disabled="!isEdit"
      >
        <el-option
          v-for="item in examineList"
          :key="item.id"
          :label="item.dictValue"
          :value="item.id"
        />
      </el-select>

      <div class="report_action">
        <el-tooltip
          class="item"
          effect="dark"
          :content="$t('caseorder.yulan.yulan114')"
          placement="bottom"
        >
          <img
            v-show="isEdit"
            src="@/assets/img/icon/screenshot_1.png"
            @click="clickScreenshotHandler()"
            alt=""
          />
        </el-tooltip>

        <el-tooltip class="item" effect="dark" :content="$t('add.add020')" placement="bottom">
          <el-popconfirm v-show="isEdit" :title="$t('caseorder.anli74')" @confirm="toDeleteShot()">
            <img src="@/assets/img/icon/delete_1.png" slot="reference" alt="" />
          </el-popconfirm>
        </el-tooltip>

        <el-tooltip class="item" effect="dark" :content="$t('add.add065')" placement="bottom">
          <img src="@/assets/img/icon/close_1.png" @click="colse" alt="" />
        </el-tooltip>
      </div>
    </div>

    <div class="body">
      <reviewList ref="reviewList" :res_form="res_form" :isEdit="isEdit" :isshowQualified="false" />
    </div>

    <div class="footer" v-show="isEdit">
      <el-button size="small" @click="action('save')">
        <el-tooltip class="item" effect="dark" :content="$t('caseorder.yulan.yulan27')" placement="top">
          <span class="ellipsis" style="width: 50px">{{
            $t('caseorder.yulan.yulan27')
          }}</span>
        </el-tooltip>
        
      </el-button>
      <el-button size="small" @click="action('refuse')">
        <el-tooltip class="item" effect="dark" :content="$t('caseorder.yulan.yulan28')" placement="top">
          <span class="ellipsis" style="width: 50px">{{
             $t('caseorder.yulan.yulan28')
           }}</span>
        </el-tooltip>
        
      </el-button>
      <el-button size="small" @click="action('confirm')" type="primary">
        <el-tooltip class="item" effect="dark" :content="$t('caseorder.yulan.yulan29')" placement="top">
          <span  class="ellipsis" style="width: 50px">{{
             $t('caseorder.yulan.yulan29')
           }}</span>
        </el-tooltip>
       
      </el-button>
    </div>

    <!-- 自制截图插件 -->
    <!-- <madeScreenshots ref="madeScreenshots" v-show="madeScreenshots" :res_form="res_form"
      @changeData="changeScreenshotData" @closeScreenshot="closeScreenshot"></madeScreenshots> -->
    <!-- 截图的审核项部分 -->

    <!-- 点击确认 拒绝接单后出现的审核预览弹窗 -->
    <el-dialog
      v-loading="reportPreview_loading"
      :element-loading-text="$t('caseorder.anli97')"
      class="reportPreview_dialog"
      top="5vh"
      :title="$t('caseorder.anli78')"
      :visible.sync="reportVisible"
      width="70%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <reportPreview
        :isShowConfirmText="true"
        ref="report_preview"
        v-if="reportVisible"
        :isConfirm="isConfirm"
        :res_form="res_form"
        :is3column="true"
      />
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="reportCancel">{{ $t('add.add31') }}</el-button>
        <el-button
          :loading="reportPreview_loading"
          size="small"
          type="primary"
          @click="reportConfirm"
        >
          {{ isConfirm === 'true' ? $t('caseorder.yulan.yulan29') : $t('caseorder.yulan.yulan28') }}
        </el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import ScreenShort from 'js-web-screen-shot';

import reportPreview from '@/views/order/common/reportPreview';

import reviewList from '@/views/order/common/reviewList';

import madeScreenshots from '@/views/order/common/madeScreenshots';
export default {
  name: 'BLZMasterReportresult',

  data() {
    return {
      examineTyle: '',
      examineList: [],

      res_form: {
        remarks: '',
        items: [],
      },
      // 截图之后出现的弹框部分
      dialogVisible: false,

      examineRules: {
        examineTyle: [{ required: true, message: this.$t('caseorder.anli79'), trigger: 'change' }],

        description: [{ required: true, message: this.$t('caseorder.anli77'), trigger: 'blur' }],
      },

      // 审核报告部分
      reportVisible: false,
      isConfirm: 'false',

      timer: null,
      screenShotHandler: null,
      loading: true,
      reportPreview_loading: false,

      // 控制自制截图组件显示
      madeScreenshots: false,
    };
  },
  props: {
    // 是否编辑
    isEdit: {
      type: Boolean,
    },
    // 数据传输
    dataObj: {
      type: Object,
    },
    /***
     * 0: 不跳出审核预览弹框
     * 1：拒绝接单弹框
     * 2: 确认接单弹框
     */
    acitonType: {
      type: String,
    },
  },
  watch: {
    dataObj: {
      handler() {
        this.initReportType();
      },
      deep: true,
    },
    acitonType: {
      handler(newVal) {
        this.showConfirmFrame();
      },
      deep: true,
    },
  },
  components: {
    reportPreview,
    reviewList,
    madeScreenshots,
  },
  created() {
    this.isConfirm = this.$route.query.isConfirm;
    this.initReportType();
    // 获取报告类型下拉框数据列表
    this.getReportTypes();

    // 向后端刷审核报告编辑状态改变接口
    if (this.isEdit) {
      this.toEditingStatus();
      this.refreshReportState();
    }

    this.showConfirmFrame();
  },

  methods: {
    // 初始化报告类型
    initReportType() {
      if (this.dataObj.order.reportType) {
        this.examineTyle = this.dataObj.order.reportType;
      } else {
        let languageType = localStorage.getItem('lang');
        if (this.acitonType) {
          // 判断是中英文
          if (languageType) {
            this.initLanguageReport(languageType);
          } else {
            this.initLanguageReport('cn');
          }
        } else {
          this.initLanguageReport(languageType);
        }
      }
    },
    // 中英文下初始化报表类型
    initLanguageReport(languageType) {
      if (languageType === 'cn') {
        // 中文
        if (this.dataObj.order.orderDataType == 1) {
          // 牙齿修复
          this.examineTyle = '52';
        } else if (this.dataObj.order.orderDataType == 2) {
          // 牙齿种植
          this.examineTyle = '53';
        } else if (this.dataObj.order.orderDataType == 3) {
          // 牙齿正畸
          this.examineTyle = '54';
        }
      } else if (languageType === 'en') {
        // 英文
        if (this.dataObj.order.orderDataType == 1) {
          // 牙齿修复
          this.examineTyle = '90';
        } else if (this.dataObj.order.orderDataType == 2) {
          // 牙齿种植
          this.examineTyle = '91';
        } else if (this.dataObj.order.orderDataType == 3) {
          // 牙齿正畸
          this.examineTyle = '92';
        }
      } else if (languageType === 'pt') {
        // 英文
        if (this.dataObj.order.orderDataType == 1) {
          // 牙齿修复
          this.examineTyle = '130';
        } else if (this.dataObj.order.orderDataType == 2) {
          // 牙齿种植
          this.examineTyle = '131';
        } else if (this.dataObj.order.orderDataType == 3) {
          // 牙齿正畸
          this.examineTyle = '132';
        }
      }
    },
    // 初始化是否打开确认接单 拒绝接单弹框
    showConfirmFrame() {
      console.log('acitonType--------', this.acitonType);
      if (this.acitonType === '0') {
      } else if (this.acitonType === '1') {
        this.action('refuse');
      } else if (this.acitonType === '2') {
        this.action('confirm');
      }
    },
    refreshReportState() {
      this.timer = setInterval(() => {
        this.toEditingStatus();
      }, 10 * 1000);
    },
    // 定义一个方法发送心跳
    toEditingStatus() {
      let user_realName = window.localStorage.getItem('user_realName');
      this.$http
        .get(
          `/digitalImpression/editingStatus?orderId=${this.$route.query.id}&curUser=${user_realName}`,
        )
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    getReportTypes() {
      this.$http
        .get('/sys/dict/data/showDictData?dictTypeId=10')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
      
            this.examineList = res.data;
            if (!this.examineTyle) {
              this.examineTyle = this.examineList[0].id;
            }

            this.typeChange();
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    typeChange() {
      this.$http
        .get('/sys/dict/data/showDictData?dictTypeId=' + this.examineTyle)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            const formData = new FormData();
            formData.append('orderId', this.$route.query.id);
            this.$http
              .post(
                '/digitalImpression/showDigitalImpression?reportType=' + this.examineTyle,
                formData,
              )
              .then(({ data: echoRes }) => {
                if (echoRes.code !== 0) {
                  return this.$message.error(echoRes.msg);
                } else {
                
                  let res_form = JSON.parse(JSON.stringify(this.res_form));
                  if (echoRes.data.data && echoRes.data.data.length > 0) {
                    res_form.remarks = echoRes.data.data[0].notes;
                  } else {
                    res_form.remarks = '';
                  }
                  res_form.items = res.data;
                  let checkCount = 0;
                  if (res_form.items && res_form.items.length > 0) {
                    res_form.items.forEach((item) => {
                      if (echoRes.data.data && echoRes.data.data.length > 0) {
                        item['check'] = echoRes.data.data[0][item.keyItem];
                        item['check'] = item['check'] === '1' ? true : false;
                        if (item['check']) {
                          checkCount++;
                        }
                      } else {
                        if (this.acitonType === '1') {
                          item['check'] = false;
                        } else if (this.acitonType === '2') {
                          item['check'] = true;
                        } else {
                          item['check'] = false;
                        }
                      }

                      item['list'] = [];
                      if(echoRes.data && echoRes.data.reportTypeItem && echoRes.data.reportTypeItem.length > 0){
                        echoRes.data.reportTypeItem.forEach((item1) => {
                          if (item1.reportTypeItem === item.id) {
                            item['list'].push({
                              examineTyle: item1.reportTypeItem,
                              description: item1.problemDescription,
                              picPath: item1.fileUrl,
                              id: item1.id,
                              check: false,
                            });
                          }
                        });
                      }
                     
                    });
                  }
                  if (checkCount === res_form.items.length) {
                    res_form['isCheckAll'] = true;
                  } else {
                    res_form['isCheckAll'] = false;
                  }
                  if (echoRes.data.data && echoRes.data.data.length === 0) {
                    if (this.acitonType === '1') {
                      res_form['isCheckAll'] = false;
                    } else if (this.acitonType === '2') {
                      res_form['isCheckAll'] = true;
                    } else {
                      res_form['isCheckAll'] = false;
                    }
                  }
                  this.res_form = JSON.parse(JSON.stringify(res_form));
                  this.$EventBus.$emit('get_res_form');
                  this.loading = false;
                }
              })
              .catch((err) => {
                this.cancleLoading = false;
                console.log('err', err);
                this.loading = false;
              });
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },

    // 截图
    clickScreenshotHandler() {
      this.$emit('openScreenshot', this.res_form);
    },
    closeScreenshot() {
      this.madeScreenshots = false;
    },

    changeScreenshotData(data) {
      let res_form = JSON.parse(JSON.stringify(this.res_form));
      res_form.items.forEach((item) => {
        if (item.id === data.examineTyle) {
          if (item.list && item.list.length === 10) {
            return this.$message({
              message: this.$t('caseorder.anli100'),
              type: 'warning',
            });
          } else {
            this.$message({
              message: this.$t('caseorder.anli101'),
              type: 'success',
            });
            item.list.push({
              examineTyle: data.examineTyle,
              description: data.description,
              picPath: data.picPath,
            });
          }
        }
      });
      this.res_form = JSON.parse(JSON.stringify(res_form));

      this.madeScreenshots = false;
    },

    // 删除截图部分
    toDeleteShot() {
      let checkNum = 0;
      let form = this.$refs.reviewList.form;
      form.items.forEach((item) => {
        item.list.forEach((item1) => {
          if (item1.check) {
            checkNum++;
          }
        });
      });
      if (checkNum > 0) {
        this.action('delete');
      } else {
        this.$message({
          message: this.$t('caseorder.anli94'),
          type: 'warning',
        });
      }
    },

    // 关闭整个审核项表单
    colse() {
      this.$emit('audiChildren');
    },
    // 定义一个保存方法
    save(type, callback) {
      let reportPreview = this.$refs.report_preview;
      let languageType = localStorage.getItem('lang');
      if (languageType === undefined || languageType === null) {
        languageType = 'cn';
      }
      let form = JSON.parse(JSON.stringify(this.$refs.reviewList.form));
      if (type === 'delete') {
        form.items.forEach((item) => {
          item.list = item.list.filter((f) => !f['check']);
        });
      }
      let param = {
        data: [{}],
        dataIntegrity: [],
      };
      form.items.forEach((item) => {
        param.data[0][item['keyItem']] = item['check'] ? '1' : '0';
        param.data[0].notes = form.remarks;
        param.data[0].orderId = this.$route.query.id;
        if (reportPreview && reportPreview.reportData.generationTime) {
          param.data[0].reportTime = reportPreview.reportData.generationTime;
        }
        if (reportPreview && reportPreview.reportData.reportResult) {
          param.data[0].reportResult = reportPreview.reportData.reportResult;
        }

        item.list.forEach((picItem) => {
          param.dataIntegrity.push({
            orderId: this.$route.query.id,
            reportType: this.examineTyle,
            reportTypeItem: picItem.examineTyle,
            fileUrl: picItem.picPath,
            problemDescription: picItem.description,
            language: languageType,
          });
        });
      });

      param.data = JSON.stringify(param.data);
      param.dataIntegrity = JSON.stringify(param.dataIntegrity);
      param.orderId = this.$route.query.id;
      param.reportType = this.examineTyle;

      this.$http
        .post('/digitalImpression/save', param)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            callback && callback();
          }
        })
        .catch((err) => {
          this.cancleLoading = false;
          console.log('err', err);
        });
    },
    // 整个审核项的保存
    action(type) {
      if (type === 'save' || type === 'delete') {
        this.save(type, () => {
          if (type === 'delete') {
            this.$message.success(this.$t('caseorder.anli89'));
          } else {
            this.$message.success(this.$t('caseorder.anli88'));
          }
          this.typeChange();
        });
      } else if (type === 'refuse') {
        // 拒绝接单
        this.isConfirm = 'false';
        this.reportVisible = true;
      } else if (type === 'confirm') {
        // 确认接单
        this.isConfirm = 'true';
        this.reportVisible = true;
      }
    },

    // 审核报告中弹框的事件
    reportCancel() {
      this.reportVisible = false;
    },
    reportConfirm() {
      this.reportPreview_loading = true;
      // 不管怎么样确认接单 和 拒绝接单都会调用保存接口
      if (this.isConfirm === 'true') {
        this.save('save', () => {
          this.$refs.report_preview.reportConfirm(() => {
            this.reportVisible = false;
            this.reportPreview_loading = false;
            this.$emit('changeState');
          });
        });
      } else if (this.isConfirm === 'false') {
        // 拒绝接单
        this.save('save', () => {
          this.$refs.report_preview.refuseOrder(() => {
            this.reportVisible = false;
            this.reportPreview_loading = false;
            this.$emit('changeState');
          });
        });
      }
    },

    // 销毁弹框的编辑状态
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  },
};
</script>

<style lang="scss" scoped>
//报告
.report {
  position: relative;
  height: 100%;

  ::v-deep .el-card__header {
    height: 70px;
  }

  ::v-deep .el-card__body {
    height: calc(100% - 70px);
  }

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .report_action {
      img {
        width: 25px;

        cursor: pointer;
      }

      .el-tooltip {
        display: inline-block;
        width: 25px;

        margin-right: 10px;
      }
    }
  }

  .body {
    height: 92%;
    overflow: auto;
    padding: 10px;
  }

  .footer {
    margin-top: 4%;

    height: 4%;

    text-align: right;
  }
}

::v-deep .reportPreview_dialog .el-dialog__body {
  height: 700px;
}
</style>
